var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var MPage = require('../MPage.js');
var WxParse = require('../../utils/wxParse/wxParse.js');
var app = getApp();

Page(common.extendPage(MPage, {

  /**
   * 页面的初始数据
   */
  data: {
    winHei: 0,

    isAllSelected: true,
    allTotalPrice: 0,
    cartList: [],
    num: '',
    dataLoaded: false,
    isLoginShow: false,
    isLogin: !!app.getUserSid(),
  },

  onLoad(options) {
    this.setData({
      winHei: app.getWinHei()
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function(options) {
    var isLogin = !!app.getUserSid();

    if (isLogin) {
      this.setData({
        isLogin,
      });
      this._initcart();
    } else {
      this.setData({
        isLogin,
        dataLoaded: true
      });
    }
  },

  onLoginSuc() {
    this.setData({
      isLogin: true
    });
    this._initcart();
  },

  _showLogin() {
    this.setData({
      isLoginShow: true
    });
  },

  // 购物车初始化
  _initcart: function() {
    var self = this;
    ajax.P('/openapi/CCart/cart', {}, function(data) {
      var cartList = data.result.cartList;

      cartList.forEach(function(item) {
        item.selected = true;
      });
      self.setData({
        cartList,
        dataLoaded: true
      })
      self._getTotalPrice();
    });
  },
  //单选商品
  _bindCheckbox: function(e) {
    var self = this;
    var formId = e.detail.formId;
    var index = parseInt(e.target.dataset.index);
    var cartList = self.data.cartList;
    cartList[index].selected = !cartList[index].selected;
    self._checkAllSelected();
    self.setData({
      cartList: cartList,
    });
    self._getTotalPrice();
    common.submitForm(formId);

  },

  _checkAllSelected: function() {
    var cartList = this.data.cartList;
    var isAllSelected = false;
    var hasNoSelected = cartList.some(function(item) {
      if (!item.selected) {
        return true;
      }
    });

    if (!hasNoSelected) {
      isAllSelected = true;
    }
    this.setData({
      isAllSelected
    });
  },

  //删除商品
  _deleteList(e) {
    var _self = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var formId = e.detail.formId;
    var cartList = this.data.cartList;

    util.confirm('确定要删除这个商品吗？', function() {
      ajax.P('/openapi/CCart/del', {
        id: cartList[index].id,
      }, function(data) {
        cartList.splice(index, 1);
        _self.setData({
          cartList: cartList
        });
        _self._getTotalPrice();
      });
    });
    common.submitForm(formId);
  },

  //全选商品
  _bindAllCheck: function(e) {
    var self = this;
    var cartList = self.data.cartList;
    var formId = e.detail.formId;
    var isAllSelected = self.data.isAllSelected;

    cartList.forEach(function(item) {
      item.selected = !isAllSelected;
    });

    self.setData({
      isAllSelected: !isAllSelected,
      cartList: cartList
    });
    self._getTotalPrice();
    common.submitForm(formId);
  },

  /**
   * 增加数量
   */
  _addCount(e) {
    var self = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var cartList = this.data.cartList;
    var goods = cartList[index];
    var num = parseInt(goods.amount) + 1;
    this._modifyAmount(index, num);
  },

  // 减少数量
  _minusCount(e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var cartList = this.data.cartList;
    var num = parseInt(cartList[index].amount);
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    this._modifyAmount(index, num);
  },

  /**
   * 修改购物车数量
   */
  _modifyAmount(index, num) {
    var self = this;
    var cartList = self.data.cartList;
    var goods = cartList[index];
    ajax.P('/openapi/CCart/modifyAmount', {
      id: goods.id,
      number: num,
    }, function(data) {

      goods.amount = num;
      self.setData({
        cartList: cartList
      });
      self._getTotalPrice();
    });
  },

  //计算总价
  _getTotalPrice() {
    var cartList = this.data.cartList;
    var total = 0;
    for (var i = 0; i < cartList.length; i++) {
      if (cartList[i].selected) {
        total += parseInt(cartList[i].amount) * parseFloat(cartList[i].salePrice);
      }
    }
    this.setData({
      cartList: cartList,
      allTotalPrice: total.toFixed(2)
    });
  },
  _settleAccounts(e) {
    var cartList = this.data.cartList;
    var formId = e.detail.formId;
    var cartId = [];
    var goodsId = [];
    var skuId = [];
    var amount = [];
    cartList.forEach(function(item) {
      if (item.selected) {
        cartId.push(item.id);
        goodsId.push(item.goodsId);
        skuId.push(item.skuId);
        amount.push(item.amount);
      }
    })
    if (goodsId != "") {
      ajax.P('/openapi/CHome/showQuickBuy', {
          cartId: cartId,
          goodsId: goodsId,
          skuId: skuId,
          amount: amount
        },
        function(data) {
          wx.navigateTo({
            url: '../confirmOrder/confirmOrder?cartId=' + JSON.stringify(cartId) + '&goodsId=' + JSON.stringify(goodsId) + '&skuId=' + JSON.stringify(skuId) + '&amount=' + JSON.stringify(amount),
          })
        });
    } else {
      wx.showModal({
        title: '提示',
        content: '您还没有选择商品哦~',
        showCancel: false
      })
    }
    common.submitForm(formId);
  },
  _jump: function(evt) {
    common.jump(evt);
  }
}));